package common.myshiro;

import entity.PermissionRole;
import entity.Role;
import entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import service.UserService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义的域
 */
public class MyRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(MyRealm.class);
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("用户授权");
        String username = (String)principals.getPrimaryPrincipal();
        logger.info("当前用户===>  " + username);
        if(username == null) {
            throw new RuntimeException("该账号未登录！");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        Set<String> roles = new HashSet<String>();
//        Set<String> stringPermissions = new HashSet<String>();
//        roles.add("USER");
//        stringPermissions.add("USER:DELETE");//角色:权限

//        info.setRoles(roles);//角色可以通过数据库查询得到
//        info.setStringPermissions(stringPermissions);//权限可以通过数据库查询得到

        //通过用户名查询数据库，查询用户的角色
        Set<String> roles = new HashSet<String>();
        List<Role> roleList = userService.findRolesByUsername(username);
        if(roleList.size()>0){
            for(Role role:roleList){
                roles.add(role.getRoleCode());
            }
        }
        info.setRoles(roles);
        //通过用户名查询用户的权限
        Set<String> permissions = new HashSet<String>();
        List<PermissionRole> permissionRoleList = userService.findPermissionProleByUsername(username);
        if(roleList.size()>0){
            for(PermissionRole permissionRole:permissionRoleList){
                roles.add(permissionRole.getRoleCode());
            }
        }
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 访问登录的controller,调用Subject.login() 方法，再调用此方法，验证用户是否存在
     * @param autToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken autToken) throws AuthenticationException {
        logger.info("验证账号是否存在");
        UsernamePasswordToken userPwdToken = (UsernamePasswordToken) autToken;
        String userName = userPwdToken.getUsername();

        List<User> user = userService.findUserByID(userName);
        if (user.size() == 0) {
            throw new RuntimeException("账号 [ " + userName + " ]不存在！" );
        }
//
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.get(0).getUsername(), user.get(0).getPassword(), getName());

        return authenticationInfo;
    }


}
